﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Xml;
using ServBus.ListForm2010.Utility;
using System.IO;

namespace ServBus.ListForm2010.ListFormWebPart
{
    [ToolboxItemAttribute(false)]
    public class ListFormWebPart : WebPart
    {
        // 当更改可视 Web 部件项目项时，Visual Studio 可能会自动更新此路径。
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/ServBus.ListForm2010/ListFormWebPart/ListFormWebPartUserControl.ascx";
        
        protected override void CreateChildControls()
        {
            ListFormWebPartUserControl control = Page.LoadControl(_ascxPath) as ListFormWebPartUserControl;
            if (control != null)
            {
                control.webpart = this;
            }
            Controls.Add(control);
        }


        #region Properties
        private bool _ShowRibbon = true;
        [WebBrowsable(true)]
        [WebDescription("ShowRibbon")]
        [WebDisplayName("ShowRibbon")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool ShowRibbon
        {
            get { return _ShowRibbon; }
            set
            { _ShowRibbon = value;
            }
        }

        [WebDescription("ViewName")]
        [WebDisplayName("ViewName")]
        [Personalizable(PersonalizationScope.Shared)]
        public string ViewName { get; set; }

        
        //[WebBrowsable(true)]
        //[WebDescription("listId")]
        //[WebDisplayName("listId")]
        //[Personalizable(PersonalizationScope.Shared)]
        //public string listId { get; set; }

        //[WebBrowsable(true)]
        //[WebDescription("ctypeId")]
        //[WebDisplayName("ctypeId")]
        //[Personalizable(PersonalizationScope.Shared)]
        //public string ctypeId { get; set; }
        #endregion

        public override EditorPartCollection CreateEditorParts()
        {

            EditorPartCollection baseParts = base.CreateEditorParts();

            List<EditorPart> editorParts = new List<EditorPart>(1);

            EditorPart part = new MyEditorPart();

            part.ID = this.ID + "_tagValueEditor";

            part.Title = "InfoPath Form";

            editorParts.Add(part);

            return new EditorPartCollection(baseParts, editorParts);

        }
    }



    #region EditorPart

    public class MyEditorPart : EditorPart
    {
        private DropDownList ddl_View;
        private CheckBox cb_ShowRibbon;

        private Dictionary<string, string> urlParamDic = new Dictionary<string, string>();
        private void DecodeUrl()
        {
            String currurl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl.ToUpper());
            String querystring = null;

            // Check to make sure some query string variables
            // exist and if not add some and redirect.
            int iqs = currurl.IndexOf('?');
            if (iqs >= 0)
            {
                querystring = (iqs < currurl.Length - 1) ? currurl.Substring(iqs + 1) : String.Empty;
            }

            // Parse the query string variables into a NameValueCollection.
            System.Collections.Specialized.NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

            // Iterate through the collection.
            foreach (String s in qscoll.AllKeys)
            {
                urlParamDic.Add(s, qscoll[s]);
            }
        }

        private string Request(string param)
        {
            string returnValue = string.Empty;

            if (urlParamDic.ContainsKey(param.ToUpper()))
            {
                returnValue = urlParamDic[param.ToUpper()];
            }
            return returnValue;
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            
            cb_ShowRibbon = new CheckBox();
            cb_ShowRibbon.Text = "Show InfoPath Ribbon or toolbar<br />";
            Label alterLine = new Label();
            alterLine.Text = "<div style='width:100%' class='UserDottedLine'></div>";
            ddl_View = new DropDownList();
            Label lbl_View = new Label();
            lbl_View.Text = "<br />Select the form view to display by default.<br /><br />Views:<br />";
            List<string> listViews = getViews();
            foreach (string formView in listViews)
            {
                string formViewId = formView.Substring(0, formView.IndexOf('_'));
                string formViewName = formView.Substring(formView.IndexOf('_') + 1);
                ListItem listItem = new ListItem(formViewName, formViewName);
                ddl_View.Items.Add(listItem);
                
            }
            Label alterLine1 = new Label();
            alterLine1.Text = "<br /><br />";
            Controls.Add(cb_ShowRibbon);
            Controls.Add(alterLine);
            Controls.Add(lbl_View);
            Controls.Add(ddl_View);
            Controls.Add(alterLine1);
        }

        private List<string> getViews()
        {
            List<string> views = new List<string>();
            byte[] xsnContent = null;
            using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb _web = _site.OpenWeb(SPContext.Current.Web.ID))
                {
                    DecodeUrl();
                    string ctypeId = Request("ctypeId");
                    string listId = Request("listId");
                    Guid guid_listId = new Guid(listId);
                    SPList _list = _web.Lists[guid_listId];
                    SPContentTypeId _ctypeId = new SPContentTypeId(ctypeId.ToLower());
                    SPContentType _cType = _list.ContentTypes[_ctypeId];
                    string _xsnLocation = _web.Url + "/" + _cType.ResourceFolder.Url + "/template.xsn";
                    SPFile file = _web.GetFile(_xsnLocation);
                    xsnContent = file.OpenBinary();
                    XmlDocument xsfDoc = new XmlDocument();
                    XsnExtractor extractor = new XsnExtractor(xsnContent);
                    byte[] xsfContent = extractor.Extract("manifest.xsf");
                    using (MemoryStream xsfStream = new MemoryStream(xsfContent))
                    {
                        xsfDoc.Load(xsfStream);
                    }

                    // Validate Feature
                    FeatureChecker checker = new FeatureChecker(xsfDoc);
                    views = checker.ViewInfo;
                }
            }
            return views;
        }
        

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            ListFormWebPart webPart = WebPartToEdit as ListFormWebPart;
            if (webPart != null)
            {
                webPart.ShowRibbon = cb_ShowRibbon.Checked;
                webPart.ViewName = ddl_View.SelectedValue.ToString();

            }
            return true;
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            ListFormWebPart webPart = WebPartToEdit as ListFormWebPart;
            if (webPart != null)
            {
                cb_ShowRibbon.Checked = webPart.ShowRibbon;
                ddl_View.SelectedValue = webPart.ViewName;
            }
        }
    }
    #endregion
}
